#include "../include/utils/memory_manager.h"
#include <windows.h>
#include <psapi.h>
#include <iostream>

std::unordered_map<std::string, size_t> MemoryManager::memory_usage_;
std::mutex MemoryManager::mutex_;

size_t MemoryManager::getCurrentRSS() {
    PROCESS_MEMORY_COUNTERS pmc;
    GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc));
    return pmc.WorkingSetSize;
}

size_t MemoryManager::getPeakRSS() {
    PROCESS_MEMORY_COUNTERS pmc;
    GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc));
    return pmc.PeakWorkingSetSize;
}

void MemoryManager::trackMemory(const std::string& tag, size_t size) {
    std::lock_guard<std::mutex> lock(mutex_);
    memory_usage_[tag] += size;
}

void MemoryManager::printMemoryUsage() {
    std::lock_guard<std::mutex> lock(mutex_);
    std::cout << "\n=== Memory Usage Report ===" << std::endl;
    std::cout << "Current RSS: " << getCurrentRSS() / (1024 * 1024) << " MB" << std::endl;
    std::cout << "Peak RSS: " << getPeakRSS() / (1024 * 1024) << " MB" << std::endl;
    
    std::cout << "\nTracked Memory by Tag:" << std::endl;
    for (const auto& entry : memory_usage_) {
        std::cout << entry.first << ": " << entry.second / 1024 << " KB" << std::endl;
    }
}

void MemoryManager::checkLeaks() {
    std::lock_guard<std::mutex> lock(mutex_);
    if (!memory_usage_.empty()) {
        std::cerr << "Potential memory leaks detected!" << std::endl;
        printMemoryUsage();
    }
}